/*
 *  Copyright 2011 yura.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.vcforms.view;

import java.util.Properties;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import org.opu.vcforms.bean.EventBus;
import org.opu.vcforms.resource.ResourceHandle;

/**
 *
 * @author yura
 */
public class ApplicationMenuBar extends JMenuBar{
    private static final String MAIN_PROP = "MenuBar";
    private static final String MENU_PATH = "/org/opu/vcforms/view/Menu.properties";
    
    private EventBus events;
    private ApplicationMenuBarI18n i18n;

    public ApplicationMenuBar(EventBus events, ApplicationMenuBarI18n i18n) {
        this.events = events;
        this.i18n = i18n;
        Properties prop = ResourceHandle.loadProperties(null, MENU_PATH);
        initMenuBar(prop);
    }

    private void initMenuBar(Properties data){
        String property = data.getProperty(MAIN_PROP);
        String[] split = property.split(";");
        for (int i = 0; i < split.length; i++) {
            String string = split[i].trim();
            //if it`s menu
            if (string.charAt(0) == '%'){
                String name = string.substring(1);
                add(getMenu(data, MAIN_PROP + "." + name, name));
            }
            //it`s menu item (it`s bad if item on menubar)
            else {
                add(getMenuItem(string));
            }
        }
    }

    private JMenu getMenu(Properties data, String property, String name){
        JMenu menu = new JMenu(i18n.getMenuText(name));
        String propertyData = data.getProperty(property);
        String[] split = propertyData.split(";");
        for (int i = 0; i < split.length; i++) {
            String string = split[i].trim();
            //if it`s menu
            if (string.charAt(0) == '%'){
                String _name = string.substring(1);
                menu.add(getMenu(data, MAIN_PROP + "." + _name, _name));
            }
            //if it`s separator
            if (string.charAt(0) == '-'){
                menu.addSeparator();
            }
            //it`s menu item (it`s bad if item on menubar)
            else {
                menu.add(getMenuItem(string));
            }
        }
        return menu;
    }

    private JMenuItem getMenuItem(String name){
        return new JMenuItem(events.getAction(name));
    }

}
